package com.von.nhcf.mvc.controller;

import com.von.nhcf.entity.Menu;
import com.von.nhcf.service.MenuService;
import com.von.nhcf.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单控制器
 * @author von
 */
@Controller
public class MenuController {
    @Autowired
    private MenuService menuService;

    @RequestMapping("menu/do/delete.json")
    @ResponseBody
    public ResultEntity doDelete(Integer id) {
        menuService.deleteById(id);
        return ResultEntity.successWithoutData();
    }
    @RequestMapping("menu/do/update.json")
    @ResponseBody
    public ResultEntity doUpdate(Menu menu) {
        menuService.updateMenu(menu);
        return ResultEntity.successWithoutData();
    }
    @RequestMapping("/menu/do/save.json")
    @ResponseBody
    public ResultEntity doSave(Menu menu) {
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/do/build/tree.json")
    @ResponseBody
    public ResultEntity<Menu> getWholeTreeNew() {
        List<Menu> menuList = menuService.getAll();
        // 声明一个变量用来存储找到的根节点
        Menu root = null;
        // 创建 Map 对象用来存储 id 和 Menu 对象的对应关系便于查找父节点
        Map<Integer, Menu> menuMap = new HashMap<>(menuList.size());
        // 遍历 menuList 填充 menuMap
        for (Menu menu : menuList) {
            Integer id = menu.getId();
            menuMap.put(id, menu);
        }
        // 再次遍历 menuList 查找根节点、 组装父子节点
        for (Menu menu : menuList) {
            // 获取当前 menu 对象的 pid 属性值
            Integer pid = menu.getPid();
            // 如果 pid 为 null， 则为根节点
            if(pid == null) {
                root = menu;
                continue;
            }
            // 如果 pid 不为 null， 说明当前节点有父节点
            Menu father = menuMap.get(pid);
            father.getChildren().add(menu);
        }
        return ResultEntity.successWithData(root);
    }
}
